package gz.metro.datasync.service;


import com.alibaba.fastjson.JSONObject;
import gz.metro.datasync.entity.form.OrgDataForm;
import gz.metro.datasync.entity.model.SyncOrgModel;
import gz.metro.datasync.mapper.OrgSyncMapper;
import gz.metro.datasync.utils.JdbcHelper;
import gz.metro.datasync.utils.RequestParam;
import gz.metro.datasync.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @author Feily
 * @功能描述 组织增量同步数据服务类
 * @创建时间 2018-07-31
 */
@Slf4j
@Service
public class OrgSyncService extends SyncService {

    @Autowired
    private OrgSyncMapper orgSyncMapper;

    @Autowired
    private JdbcHelper jdbcHelper;

    @Autowired
    private DataClientService dataClientService;

    /**
     * 构建函数
     */
    @PostConstruct
    public void init() throws DocumentException {
        this.syncType = "org";
        this.syncConfigDocPath = "/config/sync-org-config.xml";

        if(useCustomSql){
            this.getLastSyncTimeSql = this.getSqlContent("uuap-org-getLastSyncTime");
            this.saveTargetDataSql = this.getSqlContent("uuap-org-saveTargetData");
            this.updateTargetDataSql = this.getSqlContent("uuap-org-updateTargetData");
            this.deleteTargetDataSql = getSqlContent("uuap-org-deleteTargetData");
        }else{
            this.getLastSyncTimeSql = this.buildGetLastUpdateTimeSql();
            this.saveTargetDataSql = this.buildSaveTargetDataSql();
            this.updateTargetDataSql = this.buildUpdateTargetDataSql();
            this.deleteTargetDataSql = this.buildDeleteTargetDataSql();
        }

        //删除组织同步中间表数据SQL
        this.deleteSyncDataSql = this.getSqlContent("uuap-org-deleteSyncData");
    }

    @Override
    public Result deleteSyncData() {
        log.info("deleteSyncData");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("tenantCode", this.tenantCode);
        // 删除组织同步表
        jdbcHelper.execute(this.deleteSyncDataSql,params);
        return new Result();
    }



    @Override
    public Result saveSyncData(List<Object> syncData) {
        log.info("saveSyncData");

        // 保存组织
        List<SyncOrgModel> syncOrgList = JSONObject.parseArray(JSONObject.toJSONString(syncData), SyncOrgModel.class);
        orgSyncMapper.saveBatch(syncOrgList);

        return new Result();
    }

    @Transactional
    @Override
    public Result syncTargetData() {
        log.info("syncTargetData");

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("so.tenantCode", this.tenantCode);

        // 删除目标表中的已删除数据
        if (this.physicallyDelete) {
            jdbcHelper.execute(this.deleteTargetDataSql,params);
        }

        // 修改目标组织数据
        jdbcHelper.execute(this.updateTargetDataSql,params);

        // 保存目标组织数据
        jdbcHelper.execute(this.saveTargetDataSql,params);

        return new Result();
    }

    @Override
    public List<Object> getSyncDataList(Date lastSyncTime) {
        log.info("getSyncDataList");
        log.info("lastSyncTime：{}", lastSyncTime);

        List<Object> list = new ArrayList<Object>();


        RequestParam requestParam = new RequestParam();
        requestParam.setUpdateBeginDate(lastSyncTime);
        requestParam.setUpdateEndDate(new Date());

        Result<List<OrgDataForm>> resultEntity = dataClientService.queryOrgs(requestParam);
        if (!resultEntity.isSuccess()) {
            throw new RuntimeException(resultEntity.getMessage());
        }

        // 构建数据
        List<OrgDataForm> orgs = resultEntity.getBusinessObject();
        for (OrgDataForm orgDataForm : orgs) {

            // 构建组织
            SyncOrgModel org = new SyncOrgModel();
            orgDataForm.copyTo(org);
            org.setTenantCode(this.tenantCode);

            org.setSyncId(UUID.randomUUID().toString());
            org.setSyncTime(new Date());
            org.setIsSync(true);
            list.add(org);

        }
        return list;
    }

}
